#include<websocketpp/config/asio_no_tls.hpp>
#include<websocketpp/server.hpp>
#include<functional>

using server_t = websocketpp::server<websocketpp::config::asio>; 
// 注意回调函数不能用引用
void onOpen(websocketpp::connection_hdl hdl)
{
    std::cout<<"执行链接建立的回调函数"<<std::endl;
}
void onClose(websocketpp::connection_hdl hdl)
{
    std::cout<<"执行链接断开的回调函数"<<std::endl;
}
void on_Message(server_t *server, websocketpp::connection_hdl hdl, server_t::message_ptr mesg)
{
    // 获取有效载荷
    std::string body = mesg->get_payload();
    std::cout<<"收到数据# "<<body<<std::endl;
    // 获取链接
    auto connection =  server->get_con_from_hdl(hdl);
    // 向客户端发送响应
    connection->send(body + "--from server", websocketpp::frame::opcode::value::text);
}
int main()
{
    // 实例化服务器对象
    auto server = std::make_shared<server_t>();
    // 初始化日志输出---关闭
    server->set_access_channels(websocketpp::log::alevel::none);
    // 初始化asio框架
    server->init_asio();
    // 设置连接建立、断开、获取消息回调函数
    server->set_open_handler(onOpen);
    server->set_close_handler(onClose);
    auto onMessage = std::bind(on_Message, server.get(),std::placeholders::_1, std::placeholders::_2);
    server->set_message_handler(onMessage);
    // 设置地址重用
    server->set_reuse_addr(true);
    // 设置监听端口
    server->listen(8888);
    server->start_accept();
    server->run();
}